package cn.edu.swu.lxy.rolems.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import cn.edu.swu.lxy.rolems.Role
import cn.edu.swu.lxy.rolems.MyDatabaseHelperRole
import cn.edu.swu.lxy.rolems.R

class LoveAdapter(private val context: Context, private val RoleList: List<Role>) :
    RecyclerView.Adapter<LoveAdapter.ViewHolder>() {
    private val dbHelper: MyDatabaseHelperRole = MyDatabaseHelperRole(context, "Roles.db", 2)
    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val itemImage: ImageView = view.findViewById(R.id.itemImage)
        val itemName: TextView = view.findViewById(R.id.itemName)
        val itemAttr: TextView = view.findViewById(R.id.itemAttr)
        val itemPs: TextView = view.findViewById(R.id.itemPs)
        val itemBtn: Button = view.findViewById(R.id.btn)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.loverole, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = RoleList[position]
        holder.itemImage.setImageResource(item.imageId)
        holder.itemName.text = item.name
        holder.itemAttr.text = "角色属性: "+item.attr+"元素"
        holder.itemPs.text = item.ps
        holder.itemBtn.setOnClickListener {
            val db = dbHelper.writableDatabase
            db.delete("MyRoles", "name = ? and attr = ? and ps = ? and pic = ?",
                arrayOf(item.name, item.attr, item.ps, item.imageId.toString()))
            notifyItemRemoved(position)
        }
    }

    override fun getItemCount() = RoleList.size

}